/**
 * Created by kevin on 2017/7/3.
 */
var model= require('./model');

var Docs = model.createModel({
    name: String,
    classify : {type:model.objId,ref:'DocClassifies'},
    updateUser : {type:model.objId,ref:'Users'},
    createUser : {type:model.objId,ref:'Users'},
    content : String,
    weight : {type:Number,default:4},
    utime : {type : Date,default:Date.now},
    ctime : {type : Date,default:Date.now}
},'Docs');

function listCallBack(err,list,callback) {
    if (err) {
        if (callback) {
            callback(err,list);
        }
    } else  {
        var cList = list.map(function (doc) {
            doc.createTime = doc.ctime.dynamicFotmat();
            doc.updateTime = doc.utime.dynamicFotmat();
            return doc;
        });
        if (callback) {
            callback(err,cList);
        }
    }
}

function singleCallBack(err,doc,callback) {
    if (err) {
        if (callback) {
            callback(err,doc);
        }
    } else  {
        if (doc && doc.ctime) {
            doc.createTime = doc.ctime.dynamicFotmat();
        }
        if (doc && doc.utime) {
            doc.updateTime = doc.utime.dynamicFotmat();
        }
        if (callback) {
            callback(err,doc);
        }
    }
}

Docs.getAll = function(callback) {
    Docs.find({},null,{ lean: true ,sort:{weight:1,ctime:-1}}).populate('updateUser').populate('createUser').populate('classify').exec(function (err,list) {
        listCallBack(err,list,callback);
    });
};

Docs.getByClassify = function(classify,callback) {
    Docs.find({classify : classify},null,{ lean: true ,sort:{weight:1,ctime:-1}}).populate('updateUser').populate('createUser').populate('classify').exec(function (err,list) {
        listCallBack(err,list,callback);
    });
};

Docs.getByClassifyAndLimit = function(classify,limit,callback) {
    Docs.find({classify : classify},null,{ lean: true,limit:limit ,sort:{weight:1,ctime:-1}}).populate('updateUser').populate('createUser').populate('classify').exec(function (err,list) {
        listCallBack(err,list,callback);
    });
};

Docs.getById = function (id,callback) {
    Docs.findById(id,null,{ lean: true ,sort:{weight:1,ctime:-1}}).populate('updateUser').populate('createUser').populate('classify').exec(function (err,d) {
        singleCallBack(err,d,callback);
    });
};

Docs.createUniqueName = function (doc,callback) {
    Docs.findOne({name : doc.name},function (err,d) {
        if (d) {
            if (callback) {
                callback(new Error('文档名已被占用',null));
            }
        } else  {
            Docs.create(doc,callback);
        }
    });
};

Docs.edit = function (id,doc,callback) {
    Docs.findByIdAndUpdate(id, doc, callback);
};

module.exports = Docs;